//
//  JoinWantedDetailVC.swift
//  甜言蜜语
//
//  Created by yingli_yanfa_liuxingyu on 16/7/31.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import ActionSheetPicker_3_0
import SVProgressHUD

class JoinWantedDetailVC: UIViewController ,UITableViewDelegate ,UITableViewDataSource, JoinUsWantedDetailHeadCellDelegate{
    @IBOutlet weak var tableView: UITableView!
    
    var id: Int = 0
    var type: String = ""
    var height: CGFloat?
    var lightHeight: CGFloat = 40.0
    var w: CGFloat = 0;//保存前一个button的宽以及前一个button距离屏幕边缘的距离
    var h: CGFloat = 10;//用来控制button距离父视图的高

    var modelList = JoinUsDetailModel? ()
        {
        didSet{
            self.tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "求职详情"
        let cellNib = UINib(nibName: "JoinUsWantedDetailHeadCell", bundle: nil)
        self.tableView.registerNib(cellNib, forCellReuseIdentifier: "JoinUsWantedDetailHeadCell")
        
        let cellNib1 = UINib(nibName: "JoinUsWantedDetailMiddleCell", bundle: nil)
        self.tableView.registerNib(cellNib1, forCellReuseIdentifier: "JoinUsWantedDetailMiddleCell")
        
        let cellNib2 = UINib(nibName: "JoinUsWantedDetailFooterCell", bundle: nil)
        self.tableView.registerNib(cellNib2, forCellReuseIdentifier: "JoinUsWantedDetailFooterCell")
        
        self.tableView.delegate = self
        self.tableView.dataSource = self

       self.getDeatilInfo(id, type: type)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(JoinWantedDetailVC.tableViewReload(_:)), name:"JoinUsWantJobDetail_Noti", object: nil)

    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        self.tabBarController?.tabBar.hidden = true
    }
    //移除通知
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self, name: "JoinUsWantJobDetail_Noti", object: nil)
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
        

    }
    func initRightItem(){
        
        //转发
        let ForwardBtn = UIButton(frame: CGRectMake(0, 0, 20, 20))
        ForwardBtn.setBackgroundImage(UIImage(named: "share-1-white"), forState: UIControlState.Normal)
        ForwardBtn.addTarget(self, action: #selector(self.ForwardAction), forControlEvents:  UIControlEvents.TouchUpInside)
        let Forward = UIBarButtonItem(customView: ForwardBtn)
//        let collectionBtn = UIButton(frame: CGRectMake(0, 0, 28, 28))
//        if self.modelList?.isshoucang == true{
//            collectionBtn.setBackgroundImage(UIImage(named: "collection_selected"), forState: UIControlState.Normal)
//        }else{
//            collectionBtn.setBackgroundImage(UIImage(named: "collection"), forState: UIControlState.Normal)
//        }
//        collectionBtn.addTarget(self, action: #selector(self.collectionAction), forControlEvents:  UIControlEvents.TouchUpInside)
//        let collection = UIBarButtonItem(customView: collectionBtn)
        self.navigationItem.rightBarButtonItem = Forward

    }
   
    func ForwardAction(sender: UIButton){
        self.shareAction(sender)
        
    }
    func collectionAction(sender: UIButton){
        
    }
    //MARK:MobShare
    func shareAction(sender: UIButton){
       
       let shareParames = NSMutableDictionary()
       let url = String(format: "%@jobrecruitment/qiuzhi/fenxiang/\(self.modelList!.id)",BaseUrl)
       shareParames.SSDKSetupShareParamsByText("",
                                                    images : UIImage(named: "ShareImg.png"),
                                                    url : NSURL(string:url),
                                                    title : self.modelList?.positionType!,
                                                    type : SSDKContentType.Auto)
            
            
            //2.进行分享
            SSUIShareActionSheetStyle.setShareActionSheetStyle(ShareActionSheetStyle.Simple)
            
            ShareSDK.showShareActionSheet(sender, items: nil  , shareParams: shareParames) { (state : SSDKResponseState, platformType : SSDKPlatformType, userdata : [NSObject : AnyObject]!, contentEnity : SSDKContentEntity!, error : NSError!, end) -> Void in
                
                switch state{
                    
                case SSDKResponseState.Success: print("分享成功")
                case SSDKResponseState.Fail:    print("分享失败,错误描述:\(error)")
                case SSDKResponseState.Cancel:  print("分享取消")
                    
                default:
                    break
                }
            }
        
    }
    //MARK:NetingWorking
   func getDeatilInfo(id: Int, type: String) -> Void {
        DataTool.loadJoinUsDetailData(id, type: type,completionHandler: { (newModel) in
            guard let newDataes = newModel else{
                return
            }
            self.initRightItem()
            self.modelList = newDataes
            self.tableView.reloadData()
            
        self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0,inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false)
        })
    }
    //MARK:tableviewDataSource
     func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if modelList == nil{
            return 0
        }
        if modelList?.jobimagedisplaies?.count == nil && modelList?.rmList?.count == nil{
            return 1
        }
        if modelList?.jobimagedisplaies?.count == nil || modelList?.rmList?.count == nil{
            return 2
        }else{
            return 3
        }
        
    }
     func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row == 0{
            if modelList?.requirement == ""{
                return 654
            }else{
                let font = UIFont(name: "Helvetica", size: 16)
                height = publicMethod.getLabHeigh((self.modelList?.requirement!)!, font:font!, width:SCREEN_WIDTH - 110) + 20
                
                let sport:[String] = (modelList?.lightSpot?.componentsSeparatedByString(","))!
                
                if sport.count == 0{
                    lightHeight = 0
                }
                
                for index in 0...sport.count - 1{
                    
                    let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(15)]
                    
                    let constraint = CGSize(width: 100,height: 2000)
                    
                    let size = sport[index].boundingRectWithSize(constraint, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes ,context: nil)
                
                    if 10 + w + size.width + 15 > SCREEN_WIDTH {
                        w = 0
                        
                       lightHeight = 60.0
                    }
                }

                return 654 + height! + lightHeight
                
            }
        }
        if indexPath.row == 1{
            if modelList?.jobimagedisplaies?.count == nil{
                return 0
            }else{
                var count = Int()
                count = ((modelList?.jobimagedisplaies?.count)! / 2) + ((modelList?.jobimagedisplaies?.count)! % 2)
                return 37 + 115 * CGFloat(count)
            }
            
            
        }
        if indexPath.row == 2{
            if modelList?.rmList?.count == nil{
                return 0
            }else{
                var count = Int()
                count = (modelList?.rmList?.count)!
                
                return 35 + 120 * CGFloat(count)
            }
            
        }
        return 0
        
        
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if indexPath.row == 0{
            let cell = tableView.dequeueReusableCellWithIdentifier("JoinUsWantedDetailHeadCell", forIndexPath: indexPath) as! JoinUsWantedDetailHeadCell
           
            for label in cell.lightPointView.subviews {
                label.removeFromSuperview()
            }
            cell.delegate = self
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            //用 , 符号切割字符串，"haha*hehe*xixi" ==>  "haha" "hehe" "xixi"
            var sport:[String] = (modelList?.lightSpot?.componentsSeparatedByString(","))!
            
            if modelList?.lightSpot == "" {
                sport.removeAll()
            }
            
            var w: CGFloat = 0;//保存前一个button的宽以及前一个button距离屏幕边缘的距离
            var h: CGFloat = 10;//用来控制button距离父视图的高
            if sport.count != 0 {
                
                for index in 0...sport.count - 1{
                    
                    let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(15)]
                    
                    let constraint = CGSize(width: 100,height: 2000)
                    
                    let size = sport[index].boundingRectWithSize(constraint, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes ,context: nil)
                    
                    let label: UILabel = UILabel(frame: CGRectMake(10 + w, h , size.width + 20 ,20))
                    
                    label.text = sport[index]
                    label.font = UIFont(name: "Helvetica", size: 14.0)
                    if 10 + w + size.width + 15 > SCREEN_WIDTH {
                        w = 0
                        
                        h = label.frame.height + 15
                        
                        label.frame = CGRectMake(10 + w, h, size.width + 20, 20)
                        
                        cell.lightPointViewConst.constant = 60.0
                        
                        cell.lightPointView.layoutIfNeeded()
                        
                    }
                    label.textAlignment = NSTextAlignment.Center
                    label.layer.masksToBounds = true
                    label.layer.borderWidth = 1
                    w = label.frame.origin.x + label.frame.size.width
                    
                    cell.lightPointView.addSubview(label)
                }

            }
            
            cell.iv?.sd_setImageWithURL(NSURL(string: (modelList!.imgSrc)!), placeholderImage: UIImage(named: "placeholder"))
            cell.titleLbl?.text = String(format: "%@ %@ %@岁",(modelList?.name)! ,(modelList?.sex)! ,(modelList?.age)!)
            cell.browernumLbl?.text = String(format: "已有%@人浏览",(modelList?.browerNum)!)
           // cell.unittypeLbl.text = modelList?.unitType
            cell.positiontypeLbl.text = modelList?.positionType
            cell.unitareaLbl.text = modelList?.unitArea
            cell.pay.text = modelList?.pay
            cell.ptime?.text = publicMethod.computationTimeDifference((modelList?.ptime)!)
            cell.liftLbl.text = modelList?.lift
            cell.education.text = modelList?.education
            cell.requirementLbl.text = modelList?.requirement
            cell.telLbl.text = modelList?.tel
            cell.lastunitnameLbl.text = modelList?.lastUnitName
            //cell.lastpayLbl.text = modelList?.lastpay
            cell.lastpositionLbl.text = modelList?.lastPostion
            cell.lastpayLbl.text = modelList?.pay
            cell.advertisersIv.sd_setImageWithURL(NSURL(string: (modelList?.usertimg)!), placeholderImage: UIImage(named: "placeholder"))
            cell.advertisersName.text = modelList?.username
            cell.setCellText((modelList?.requirement)!)
            
            return cell
        }
        if indexPath.row == 1{
            let cell = tableView.dequeueReusableCellWithIdentifier("JoinUsWantedDetailMiddleCell", forIndexPath: indexPath) as! JoinUsWantedDetailMiddleCell

            let cellInfo = modelList?.jobimagedisplaies
            cell.setCellContentWithCellInfo(cellInfo)
            return cell

            
        }else{
            let cell = tableView.dequeueReusableCellWithIdentifier("JoinUsWantedDetailFooterCell", forIndexPath: indexPath) as! JoinUsWantedDetailFooterCell
            
           let cellInfo = modelList?.rmList 
           cell.setCellContentWithCellInfo(cellInfo)
            return cell

            
        }
        
        
        
    }
    
   
    // MARK: - Table view delegate
     func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        
    }
    //MARK:noti
    func tableViewReload(notification:NSNotification){
        
        let id = notification.object?.valueForKey("id") as? Int
        let type = notification.object?.valueForKey("type") as? String
        
        getDeatilInfo(id!, type: type!)
       
    }
    //MARK:JoinUsWantedDetailHeadCellDelegate
    func callAction(){
        publicMethod.callPhone((self.modelList?.tel)!, withSuperView: self.view)
    }
    func reportAction(){
        ActionSheetMultipleStringPicker.showPickerWithTitle("举报", rows:[["电话虚假(如空号、无人接听)", "诈骗(个人虚假信息)", "其他"]],initialSelection: [1,1], doneBlock: {
            picker, values, indexes in
            let obj = (indexes as! NSArray)[0] as! String
            let url = String(format: "%@hzpreport/dosave",BaseUrl)
            let paramDic = ["msg": obj, "reportid": String(self.modelList!.id!), "type": "求职招聘"]
            DataTool.reportDetail(url, param: paramDic, completionHandler: ({(newModel) in
                guard newModel != nil else {
                    return
                }
                SVProgressHUD.showSuccessWithStatus(newModel?.msg)
                
            }))
            
            return
            }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: self.view)
    }
    func ivSelected() {
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("UserHomeTableViewController") as! UserHomeTableViewController
        
        vc.userId = Int((modelList?.userid)!)
        self.navigationController?.pushViewController(vc, animated: true)
    }
   
}

